﻿using DataAccess.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYD.DataAccess;
using XYD.Framework.Data;
using XYD.Framework.Data.Dapper;

namespace DataAccess.DAL
{
    public class PermissionDAL : BaseDAL
    {
        public Permission Get(int id)
        {
            return CONN_TopicSharing.Get<Permission>(id);
        }

        public bool Insert(Permission permission)
        {
            return CONN_TopicSharing.Insert<Permission>(permission);
        }

        public bool Update(Permission permission)
        {
            return CONN_TopicSharing.Update<Permission>(permission);
        }

        public List<Permission> GetPermissions()
        {
            StringBuilder sb = new StringBuilder();
             
            List<Permission> data = CONN_TopicSharing.SQLQuery<Permission>(" select * from Permission ", null).ToList();
             
            return data;
        }

        public List<Permission> GetPermissionsHierarchy()
        {
            StringBuilder sb = new StringBuilder();

            List<Permission> data = CONN_TopicSharing.SQLQuery<Permission>(" select * from Permission ", null).ToList();

            List<Permission> list = new List<Permission>();

            list = data.FindAll(p => p.parent_id == 0);

            foreach (var item in list)
            {
                item.chilids = GetChildPermissions(item.id, data);
            }

            return list;
        }
      
        public List<Permission> GetChildPermissions(int id, List<Permission> list)
        { 
            if(list.Any())
            {
                var cur = list.FindAll(p => p.parent_id == id);
                foreach (var item in cur)
                {
                    item.chilids=GetChildPermissions(item.id, list);
                }

                return cur;
            }
            return new List<Permission>();
        }

        public List<Permission> GetPermissioninRolesByUserId(int user_id)
        {

            List<Permission> data = new List<Permission>();

            StringBuilder sb = new StringBuilder();

            sb.Append(" select p.* from UserRole ur ");
            sb.Append(" left join PermissioninRole pr on pr.role_id=ur.role_id ");
            sb.Append(" left join Permission p on p.id = pr.permission_id ");
            sb.Append(" where ur.user_id=@user_id ");

            DynamicParameters dp = new DynamicParameters();
            dp.Add("@user_id", user_id);

            data = CONN_TopicSharing.SQLQuery<Permission>(sb.ToString(), dp).ToList();



            List<Permission> list = new List<Permission>();

            list = data.FindAll(p => p.parent_id == 0);

            foreach (var item in list)
            {
                item.chilids = GetChildPermissions(item.id, data);
            }

            return list;

        }
    }
}
